import axios from 'axios'

// 请求缓存 存到内存中 暂不支持localstorage
const reqCache = {}
// 默认时长 5s
const defaultMaxage = 5 * 1000
/**
 * 缓存key
 * @param config 请求config
 */
export function getKey(config) {
  const { url, method, data, params } = config
  const key = `${method}&${url}&${JSON.stringify(data) || 'data'}&${JSON.stringify(params) || 'params'}`
  return key
}
let n = 0
// 添加请求缓存
export function addReqCache(config, data) {
  const reqKey = getKey(config)
  if (config.isCache && data) {
    if (reqCache[reqKey]) {
      // 若已有缓存，则不添加(已过期的会在适配器中被删除)
      return
    }
    n++

    reqCache[reqKey] = {
      data: JSON.parse(JSON.stringify(data)),
      maxage: config.cacheMaxage ?? defaultMaxage,
      createTime: Date.now(),
      n,
    }
    console.log('添加了！')
  }
}
// 缓存适配器
export function reqCacheAdapter(config) {
  if (config.isCache) {
    const reqCacheKey = getKey(config)
    const cache = reqCache[reqCacheKey] || {}
    const response = cache?.data
    const isValid = cache.createTime && Date.now() - cache.createTime <= cache?.maxage

    console.log('n=', cache.n)
    if (response && isValid) {
      console.log('reqCache', reqCache)

      return Promise.resolve(response)
    } else if (response && !isValid) {
      // 缓存过期了，则删掉，好让其更新
      console.log('delete 之前', reqCache)
      Reflect.deleteProperty(reqCache, reqCacheKey)
      console.log('delete 之后', reqCache)
    }
  }
  // 用完得删掉本次adapter否则无限循环
  delete config.adapter
  return axios(config)
}
